<?php
/**
 * Created by PhpStorm.
 * User: aiChenK
 * Date: 2019-01-24
 * Time: 14:29
 */
namespace Services\Msg\Core\Notice;

use Helpers\Di;
use Services\Msg\Core\BaseCreator;
use Services\Msg\Models\Notice;
use Services\Msg\Models\NoticeTarget;

/**
 * 消息创建器
 * Class Creator
 * @package Services\Msg\Core
 *
 * create by ck 20190117
 */
class Creator extends BaseCreator
{
    //补充打开类型
    const VIEW_ALERT = 2;

    //消息类型
    const TYPE_INFO    = 1;
    const TYPE_SUCCESS = 2;
    const TYPE_WARNING = 3;
    const TYPE_ERROR   = 4;

    protected $title  = '您有一条新提醒';

    private $content  = '';
    private $type     = self::TYPE_INFO;

    public function setContent(string $content)
    {
        $this->content = $content;
        return $this;
    }

    public function setType($type = self::TYPE_INFO)
    {
        $this->type = $type;
        return $this;
    }

    /**
     * 验证参数
     *
     * @throws \Exception
     *
     * create by ck 20190123
     * modify by ck 20190214    添加重复验证
     */
    protected function validate()
    {
        parent::validate();

        //检查是否已创建
        $check = Notice::count([
            'conditions' => 'module = :module: AND subModule = :subModule: AND extraId = :extraId:
                            AND operate = :operate: AND isDel = 0 AND isScrap = 0',
            'bind'       => [
                'module'    => $this->module,
                'subModule' => $this->subModule,
                'extraId'   => $this->extraId,
                'operate'   => $this->operate
            ]
        ]);
        if ($check) {
            throw new \Exception('该消息已存在');
        }
    }

    /**
     * 保存消息
     *
     * @return bool
     * @throws \Exception
     *
     * create by ck 20190117
     */
    public function send()
    {
        $this->validate();
        try {
            Di::get()->db->begin();

            //写入总表
            $notice = new Notice([
                'module'    => $this->module,
                'subModule' => $this->subModule,
                'extraId'   => $this->extraId,
                'operate'   => $this->operate,
                'title'     => $this->title,
                'content'   => $this->content,
                'url'       => $this->url,
                'type'      => $this->type,
                'viewMode'  => $this->viewMode,
                'level'     => $this->level,
                'targetNum' => count($this->receiver)
            ]);
            if (!$notice->save()) {
                throw new \Exception($notice->getError());
            }

            //写入人员表
            $targetTable = (new NoticeTarget())->getSource();
            $values = [];
            foreach ($this->receiver as $receiverId) {
                $values[] = "('{$notice->id}', '{$receiverId}')";
            }
            $sql = "INSERT INTO `{$targetTable}` (`noticeId`, `targetId`) VALUES " . implode(',', $values);
            $result = Di::get()->db->execute($sql);
            if (!$result) {
                throw new \Exception('写入接收者失败');
            }

            Di::get()->db->commit();
            return true;
        } catch (\Exception $e) {
            Di::get()->db->rollback();
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * 快速发送
     *
     * @param string $title
     * @param string $content
     * @param array $receiver
     * @return bool
     *
     * create by ck 20190118
     */
    public function quickSend(string $title = '', string $content = '', $receiver = [])
    {
        if ($title) {
            $this->setTitle($title);
        }
        return $this->setContent($content)->setReceiver($receiver)->send();
    }
}
